package com.corn.juc.lock.custome;

/**
 * @author : Jim Wu
 * @version 1.0
 * @function :
 * @since : 2020/12/29 17:14
 */

public class MyReadWriteLock {

    // 正在读取的线程数
    private volatile int readThreadNum = 0;

    // 正在写入的线程数
    private volatile int writeThreadNum = 0;

    // 待写入线程数
    private volatile int writeQueue = 0;

    public synchronized void readLock() {
        try {
            readThreadNum++;
            while (writeThreadNum > 0 || writeQueue > 0) {
                wait();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public synchronized void readUnLock() {
        readThreadNum--;
        notifyAll();
    }

    public synchronized void writeLock() {
        writeQueue++;
        try {
            while (writeThreadNum > 0) {
                wait();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        writeThreadNum++;
        writeQueue--;
    }

    public synchronized void writeUnlock() {
        writeThreadNum--;
        notifyAll();
    }

}
